package com.zxj.schoolxianyu.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zxj.schoolxianyu.dao.conversationDao;
import com.zxj.schoolxianyu.dao.userDataDao;
import com.zxj.schoolxianyu.entity.conversation;
import com.zxj.schoolxianyu.entity.userData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class createConversationService {

    @Autowired(required = false)
    private conversationDao conversationDao;
    @Autowired(required = false)
    private userDataDao userDataDao;

    public String createConversation(String user1,String user2){
        EntityWrapper<conversation> c1 = new EntityWrapper<>();
        c1.eq("user1",user1);
        c1.eq("user2",user2);
        List<conversation> cs = conversationDao.selectList(c1);
        EntityWrapper<conversation> c2 = new EntityWrapper<>();
        c2.eq("user2",user1);
        c2.eq("user1",user2);
        List<conversation> cs1 = conversationDao.selectList(c2);
        if (!cs.isEmpty()){
            return JSON.toJSONString(cs.get(0));
        }
        if(!cs1.isEmpty()){
            return JSON.toJSONString(cs1.get(0));
        }
        EntityWrapper<userData> u1 = new EntityWrapper<>();
        u1.eq("username",user1);
        EntityWrapper<userData> u2 = new EntityWrapper<>();
        u2.eq("username",user2);
        conversation c = new conversation();
        c.user1=user1;
        c.user2=user2;
        c.user1img = userDataDao.selectList(u1).get(0).img;
        c.user2img= userDataDao.selectList(u2).get(0).img;
        c.lastmessage = " ";
        conversationDao.insert(c);
        return JSON.toJSONString(c);
    }
}